package cn.edu.hpu.jie.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import cn.edu.hpu.jie.util.MimeMap;

import com.opensymphony.xwork2.ActionSupport;

public class HeaderUploadAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	private File file;
	private String fileContentType;
	private String fileFileName;
	
	public String uploadHeader() throws IOException {
		if(!"POST".equals(ServletActionContext.getRequest().getMethod())) {
			sendMsg("0");
			return null;
		}
		
		if(file != null) {
			String suffix = MimeMap.getType(fileContentType);
			
			if(suffix == null) {
				sendMsg("1");
				file.delete();
				return null;
			}
			
			StringBuilder sb = new StringBuilder(ServletActionContext.getServletContext().getRealPath("/"));
			sb.append("header/");
			String savePath = sb.toString();
			
			File dirFile = new File(savePath);
			boolean result = true;
			if(!dirFile.isDirectory()) {
				result = dirFile.mkdirs();
			}
			
			if(result) {
				sb.append(fileFileName);
				
				InputStream is = new FileInputStream(file);
				OutputStream os = new FileOutputStream(new File(sb.toString()));
				
				byte[] buffer = new byte[1024];
				
				int len = -1;
				while((len = is.read(buffer)) != -1) {
					os.write(buffer, 0, len);
				}
				
				os.flush();
				is.close();
				os.close();
				
				String urlPath = sb.substring(sb.indexOf("header"));
				sendMsg("/vote/" + urlPath);
			}
			file.delete();
		}
		return null;
	}
	
	private void sendMsg(String msg) throws IOException {
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		out.println("<div id=\"msg\">" + msg + "</div>");
		out.flush();
		out.close();
	}
	
	public void setFile(File file) {
		this.file = file;
	}
	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}
	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
	
	

}
